package array.medium;

import java.util.ArrayList;
import java.util.List;

/**
 * 78. 子集
 */
public class subsets {
    public static void main(String[] args) {
        int[] t = {1, 2, 3};
        subsets subset = new subsets();
//        subset.myCode(t);
//        System.out.println(subset.result);
        System.out.println(subset.subsets(t));
    }

    List<List<Integer>> result = new ArrayList<>();
    public List<List<Integer>> myCode(int[] nums) {
        result.add(new ArrayList<>());
        for (int i = 0; i < nums.length; i++) {
            List<Integer> subList = new ArrayList<>();
            subList.add(nums[i]);
            setSubList(i + 1, nums, subList);
        }
        return result;
    }

    public void setSubList(int index, int[] nums, List<Integer> subList) {
        List<Integer> inSubList = new ArrayList<>(subList);
        if (index == nums.length) {
            result.add(inSubList);
        } else {
            setSubList(index + 1, nums, inSubList);
            inSubList.add(nums[index]);
            setSubList(index + 1, nums, inSubList);
            inSubList.remove(inSubList.size() - 1);
        }
    }

    /**
     * 回溯算法
     * @param nums
     * @return
     */
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        backtrack(0, nums, res, new ArrayList<Integer>());
        return res;

    }

    private void backtrack(int i, int[] nums, List<List<Integer>> res, ArrayList<Integer> tmp) {
        res.add(new ArrayList<>(tmp));
        for (int j = i; j < nums.length; j++) {
            tmp.add(nums[j]);
            backtrack(j + 1, nums, res, tmp);
            tmp.remove(tmp.size() - 1);
        }
    }
}
